package com.ruoyi.fun.service.impl;

import java.math.BigDecimal;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.fun.mapper.EcProductSkuMapper;
import com.ruoyi.fun.domain.EcProductSku;
import com.ruoyi.fun.service.IEcProductSkuService;

/**
 * 商品SKUService业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-06
 */
@Service
public class EcProductSkuServiceImpl implements IEcProductSkuService 
{
    @Autowired
    private EcProductSkuMapper ecProductSkuMapper;

    /**
     * 查询商品SKU
     * 
     * @param skuId 商品SKU主键
     * @return 商品SKU
     */
    @Override
    public EcProductSku selectEcProductSkuBySkuId(Long skuId)
    {
        return ecProductSkuMapper.selectEcProductSkuBySkuId(skuId);
    }

    /**
     * 查询商品SKU列表
     * 
     * @param ecProductSku 商品SKU
     * @return 商品SKU
     */
    @Override
    public List<EcProductSku> selectEcProductSkuList(EcProductSku ecProductSku)
    {
        System.out.println("[DEBUG] EcProductSkuServiceImpl.selectEcProductSkuList - 查询参数 orgId: " + ecProductSku.getOrgId());
        List<EcProductSku> result = ecProductSkuMapper.selectEcProductSkuList(ecProductSku);
        System.out.println("[DEBUG] EcProductSkuServiceImpl.selectEcProductSkuList - 查询结果数量: " + result.size());
        for (EcProductSku sku : result) {
            System.out.println("[DEBUG] EcProductSkuServiceImpl.selectEcProductSkuList - SKU ID: " + sku.getSkuId() + ", orgId: " + sku.getOrgId());
        }
        return result;
    }

    /**
     * 新增商品SKU
     * 
     * @param ecProductSku 商品SKU
     * @return 结果
     */
    @Override
    public int insertEcProductSku(EcProductSku ecProductSku)
    {
        ecProductSku.setCreateTime(DateUtils.getNowDate());
        return ecProductSkuMapper.insertEcProductSku(ecProductSku);
    }

    /**
     * 修改商品SKU
     * 
     * @param ecProductSku 商品SKU
     * @return 结果
     */
    @Override
    public int updateEcProductSku(EcProductSku ecProductSku)
    {
        ecProductSku.setUpdateTime(DateUtils.getNowDate());
        return ecProductSkuMapper.updateEcProductSku(ecProductSku);
    }

    /**
     * 批量删除商品SKU
     * 
     * @param skuIds 需要删除的商品SKU主键
     * @return 结果
     */
    @Override
    public int deleteEcProductSkuBySkuIds(Long[] skuIds)
    {
        Long orgId = SecurityUtils.getDeptId();
        return ecProductSkuMapper.deleteEcProductSkuBySkuIds(skuIds, orgId);
    }

    /**
     * 删除商品SKU信息
     * 
     * @param skuId 商品SKU主键
     * @return 结果
     */
    @Override
    public int deleteEcProductSkuBySkuId(Long skuId)
    {
        Long orgId = SecurityUtils.getDeptId();
        return ecProductSkuMapper.deleteEcProductSkuBySkuId(skuId, orgId);
    }

    /**
     * 根据skuId和组织ID查询ProductSku
     * 
     * @param skuId ProductSku主键
     * @param orgId 组织ID
     * @return ProductSku
     */
    @Override
    public EcProductSku selectEcProductSkuBySkuIdAndOrgId(Long skuId, Long orgId)
    {
        return ecProductSkuMapper.selectEcProductSkuBySkuIdAndOrgId(skuId, orgId);
    }

    /**
     * 根据组织ID查询ProductSku列表
     * 
     * @param ecproductsku ProductSku
     * @param orgId 组织ID
     * @return ProductSku集合
     */
    @Override
    public List<EcProductSku> selectEcProductSkuListByOrgId(EcProductSku ecproductsku, Long orgId)
    {
        return ecProductSkuMapper.selectEcProductSkuListByOrgId(ecproductsku, orgId);
    }

    /**
     * 导入商品SKU数据
     * 
     * @param skuList 商品SKU数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @param orgId 组织ID
     * @return 结果
     */
    @Override
    public String importSku(List<EcProductSku> skuList, Boolean isUpdateSupport, String operName, Long orgId)
    {
        if (StringUtils.isNull(skuList) || skuList.size() == 0)
        {
            throw new ServiceException("导入商品SKU数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (EcProductSku sku : skuList)
        {
            try
            {
                // 设置组织ID
                sku.setOrgId(orgId);
                
                // 设置默认值
                if (sku.getWeight() == null) {
                    sku.setWeight(new BigDecimal("0.00"));
                }
                if (sku.getVolume() == null) {
                    sku.setVolume(new BigDecimal("0.00"));
                }
                if (StringUtils.isEmpty(sku.getImage())) {
                    sku.setImage("");
                }
                if (sku.getSaleCount() == null) {
                    sku.setSaleCount(0L);
                }
                if (StringUtils.isEmpty(sku.getStatus())) {
                    sku.setStatus("0"); // 默认正常状态
                }
                if (sku.getLowStock() == null) {
                    sku.setLowStock(0L);
                }
                if (sku.getOriginalPrice() == null) {
                    sku.setOriginalPrice(sku.getPrice()); // 默认原价等于价格
                }
                if (sku.getCostPrice() == null) {
                    sku.setCostPrice(new BigDecimal("0.00"));
                }
                if (StringUtils.isEmpty(sku.getSpecInfo())) {
                    sku.setSpecInfo("");
                }
                
                // 验证这个商品SKU是否存在
                EcProductSku existingSku = null;
                if (StringUtils.isNotEmpty(sku.getSkuCode()))
                {
                    EcProductSku queryParam = new EcProductSku();
                    queryParam.setSkuCode(sku.getSkuCode());
                    queryParam.setOrgId(orgId);
                    List<EcProductSku> existingSkus = ecProductSkuMapper.selectEcProductSkuList(queryParam);
                    if (existingSkus != null && existingSkus.size() > 0)
                    {
                        existingSku = existingSkus.get(0);
                    }
                }
                
                if (StringUtils.isNull(existingSku))
                {
                    // 新增
                    sku.setCreateTime(DateUtils.getNowDate());
                    this.insertEcProductSku(sku);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、SKU编码 " + sku.getSkuCode() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    // 更新
                    sku.setSkuId(existingSku.getSkuId());
                    sku.setUpdateTime(DateUtils.getNowDate());
                    this.updateEcProductSku(sku);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、SKU编码 " + sku.getSkuCode() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、SKU编码 " + sku.getSkuCode() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、SKU编码 " + sku.getSkuCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 更新SKU销量
     * 
     * @param skuId SKU ID
     * @param increment 增量（默认为1）
     * @param orgId 组织ID
     * @return 结果
     */
    @Override
    public int updateSkuSaleCount(Long skuId, int increment, Long orgId)
    {
        System.out.println("=== 开始更新SKU销量 ===");
        System.out.println("SKU ID: " + skuId);
        System.out.println("增量: " + increment);
        System.out.println("组织ID: " + orgId);
        
        // 查询更新前的SKU信息
        EcProductSku beforeSku = ecProductSkuMapper.selectEcProductSkuBySkuId(skuId);
        if (beforeSku != null) {
            System.out.println("更新前SKU信息:");
            System.out.println("  - SKU名称: " + beforeSku.getSkuName());
            System.out.println("  - 当前销量: " + beforeSku.getSaleCount());
            System.out.println("  - SKU组织ID: " + beforeSku.getOrgId());
            System.out.println("  - SKU状态: " + beforeSku.getStatus());
        } else {
            System.out.println("警告：未找到SKU ID为 " + skuId + " 的记录！");
        }
        
        int result = ecProductSkuMapper.updateSkuSaleCount(skuId, increment, orgId);
        
        System.out.println("SQL执行结果: " + result + " (受影响的行数)");
        
        // 查询更新后的SKU信息
        if (result > 0) {
            EcProductSku afterSku = ecProductSkuMapper.selectEcProductSkuBySkuId(skuId);
            if (afterSku != null) {
                System.out.println("更新后SKU销量: " + afterSku.getSaleCount());
            }
            System.out.println("SKU销量更新成功！");
        } else {
            System.out.println("警告：SKU销量更新失败，可能原因：");
            System.out.println("1. SKU ID不存在: " + skuId);
            System.out.println("2. 组织ID不匹配: " + orgId);
            System.out.println("3. SKU状态异常");
            
            // 如果更新失败，再次查询确认SKU是否存在
            if (beforeSku != null && !orgId.equals(beforeSku.getOrgId())) {
                System.out.println("组织ID不匹配！期望: " + orgId + ", 实际: " + beforeSku.getOrgId());
            }
        }
        
        System.out.println("=== SKU销量更新完成 ===");
        return result;
    }

    /**
     * 更新SKU库存
     * 
     * @param skuId SKU ID
     * @param increment 库存增量（正数增加，负数减少）
     * @param orgId 组织ID
     * @return 结果
     */
    @Override
    public int updateSkuStock(Long skuId, Long increment, Long orgId)
    {
        System.out.println("=== 开始更新SKU库存 ===");
        System.out.println("SKU ID: " + skuId);
        System.out.println("库存增量: " + increment);
        System.out.println("组织ID: " + orgId);
        
        // 查询更新前的SKU信息
        EcProductSku beforeSku = ecProductSkuMapper.selectEcProductSkuBySkuId(skuId);
        if (beforeSku != null) {
            System.out.println("更新前SKU信息:");
            System.out.println("  - SKU名称: " + beforeSku.getSkuName());
            System.out.println("  - 当前库存: " + beforeSku.getStock());
            System.out.println("  - SKU组织ID: " + beforeSku.getOrgId());
            System.out.println("  - SKU状态: " + beforeSku.getStatus());
        } else {
            System.out.println("警告：未找到SKU ID为 " + skuId + " 的记录！");
        }
        
        int result = ecProductSkuMapper.updateSkuStock(skuId, increment, orgId);
        
        System.out.println("SQL执行结果: " + result + " (受影响的行数)");
        
        // 查询更新后的SKU信息
        if (result > 0) {
            EcProductSku afterSku = ecProductSkuMapper.selectEcProductSkuBySkuId(skuId);
            if (afterSku != null) {
                System.out.println("更新后SKU库存: " + afterSku.getStock());
            }
            System.out.println("SKU库存更新成功！");
        } else {
            System.out.println("警告：SKU库存更新失败，可能原因：");
            System.out.println("1. SKU ID不存在: " + skuId);
            System.out.println("2. 组织ID不匹配: " + orgId);
            System.out.println("3. SKU状态异常");
            
            // 如果更新失败，再次查询确认SKU是否存在
            if (beforeSku != null && !orgId.equals(beforeSku.getOrgId())) {
                System.out.println("组织ID不匹配！期望: " + orgId + ", 实际: " + beforeSku.getOrgId());
            }
        }
        
        System.out.println("=== SKU库存更新完成 ===");
        return result;
    }
}